package top.maof.book.service.myImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.maof.book.dao.RoleMapper;
import top.maof.book.model.Role;
import top.maof.book.result.PageData;
import top.maof.book.result.PageWrap;
import top.maof.book.service.RoleService;
import top.maof.book.utils.Utils;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageData<Role> findPage(PageWrap<Role> pageWrap) {
        IPage<Role> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.lambda().eq(Role::getId, pageWrap.getModel().getId());
        }
        if (pageWrap.getModel().getLevel() != null) {
            queryWrapper.lambda().eq(Role::getLevel, pageWrap.getModel().getLevel());
        }
        if (pageWrap.getModel().getSynopsis() != null) {
            queryWrapper.lambda().eq(Role::getSynopsis, pageWrap.getModel().getSynopsis());
        }
        for (PageWrap.SortData sortData : pageWrap.getSorts()) {
            if (sortData.getDirection().equalsIgnoreCase(PageWrap.DESC)) {
                queryWrapper.orderByDesc(sortData.getProperty());
            } else {
                queryWrapper.orderByAsc(sortData.getProperty());
            }
        }
        return PageData.from(roleMapper.selectPage(page, queryWrapper));
    }

    @Override
    public int add(Role role) {
        return roleMapper.insert(role);
    }

    @Override
    public Role find(int id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public int update(Role role) {
        return roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public int delete(int id) {
        return roleMapper.deleteByPrimaryKey(id);
    }
}
